package com.luoqiz.file.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.compress.utils.Lists;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFFootnote;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc;

import com.google.common.base.CharMatcher;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WordUtils {

	public static void writDocx() throws IOException, InvalidFormatException {

		XWPFDocument xwpf = new XWPFDocument();

		XWPFFootnote footnote = xwpf.createFootnote();
		XWPFParagraph para = footnote.createParagraph();
		XWPFRun run = para.createRun();
		run.setBold(true);
		run.setText("加粗的字体");
		run.setColor("FF0000");
		run.setText("标红的颜色");
//		xwpf.createChart(100, 100).setTitleText("这个title是什么");
		File file = new File("d:/test/docTest.docx");
		if (!file.exists()) {
			file.createNewFile();
		}
		System.out.println("shanchu");

		XWPFRun rs = xwpf.createParagraph().createRun();
		rs.setBold(true);
		rs.setText("加粗的字体");
		rs.setColor("FF0000");
		rs.setText("标红的颜色");
		OutputStream stream = new FileOutputStream(file);
		xwpf.write(stream);
		stream.flush();
		stream.close();
		xwpf.close();

	}

	/**
	 * 基本的写操作
	 * 
	 * @throws Exception
	 */
	public static void testSimpleWrite() throws Exception {
		// 新建一个文档
		XWPFDocument doc = new XWPFDocument();
		// 创建一个段落
		XWPFParagraph para = doc.createParagraph();

		// 一个XWPFRun代表具有相同属性的一个区域。
		XWPFRun run = para.createRun();
		run.setBold(true); // 加粗
		run.setText("加粗的内容");
		run = para.createRun();
		run.setColor("FF0000");
		run.setText("红色的字。");
		OutputStream os = new FileOutputStream("D:\\simpleWrite.docx");
		// 把doc输出到输出流
		doc.write(os);
		close(os);
	}

	/***
	 * 写一个表格
	 * 
	 * @throws Exception
	 */
	public void testWriteTable() throws Exception {
		XWPFDocument doc = new XWPFDocument();
		// 创建一个5行5列的表格
		XWPFTable table = doc.createTable(5, 5);
		// 这里增加的列原本初始化创建的那5行在通过getTableCells()方法获取时获取不到，但通过row新增的就可以。
//	    table.addNewCol(); //给表格增加一列，变成6列  
		table.createRow(); // 给表格新增一行，变成6行
		List<XWPFTableRow> rows = table.getRows();
		// 表格属性
		CTTblPr tablePr = table.getCTTbl().addNewTblPr();
		// 表格宽度
		CTTblWidth width = tablePr.addNewTblW();
		width.setW(BigInteger.valueOf(8000));
		XWPFTableRow row;
		List<XWPFTableCell> cells;
		XWPFTableCell cell;
		int rowSize = rows.size();
		int cellSize;
		for (int i = 0; i < rowSize; i++) {
			row = rows.get(i);
			// 新增单元格
			row.addNewTableCell();
			// 设置行的高度
			row.setHeight(500);
			// 行属性
//	       CTTrPr rowPr = row.getCtRow().addNewTrPr();  
			// 这种方式是可以获取到新增的cell的。
//	       List<CTTc> list = row.getCtRow().getTcList();  
			cells = row.getTableCells();
			cellSize = cells.size();
			for (int j = 0; j < cellSize; j++) {
				cell = cells.get(j);
				if ((i + j) % 2 == 0) {
					// 设置单元格的颜色
					cell.setColor("ff0000"); // 红色
				} else {
					cell.setColor("0000ff"); // 蓝色
				}
				// 单元格属性
				CTTcPr cellPr = cell.getCTTc().addNewTcPr();
				cellPr.addNewVAlign().setVal(STVerticalJc.CENTER);
				if (j == 3) {
					// 设置宽度
					cellPr.addNewTcW().setW(BigInteger.valueOf(3000));
				}
				cell.setText(i + ", " + j);
			}
		}
		// 文件不存在时会自动创建
		OutputStream os = new FileOutputStream("D:\\table.docx");
		// 写入文件
		doc.write(os);
		close(os);
	}

	/**
	 * 关闭输出流
	 * 
	 * @param os
	 */
	private static void close(OutputStream os) {
		if (os != null) {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static <T> List<String> readWordFile(String path) {
		List<String> contextList = Lists.newArrayList();
		InputStream stream = null;
		try {
			stream = new FileInputStream(new File(path));
			if (path.endsWith(".doc")) {
				HWPFDocument document = new HWPFDocument(stream);
				WordExtractor extractor = new WordExtractor(document);
				String[] contextArray = extractor.getParagraphText();
				Arrays.asList(contextArray)
						.forEach(context -> contextList.add(CharMatcher.whitespace().removeFrom(context)));
				extractor.close();
				document.close();
			} else if (path.endsWith(".docx")) {
				XWPFDocument document = new XWPFDocument(stream).getXWPFDocument();
				List<XWPFParagraph> paragraphList = document.getParagraphs();
				paragraphList.forEach(paragraph -> contextList
						.add(CharMatcher.whitespace().removeFrom(paragraph.getParagraphText())));
				document.close();
			} else {
				log.debug("此文件{}不是word文件", path);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != stream)
				try {
					stream.close();
				} catch (IOException e) {
					e.printStackTrace();
					log.debug("读取word文件失败");
				}
		}
		return contextList;
	}

	public static void main(String[] args) {
		try {
//				writDocx();
//				testSimpleWrite();

			List<String> content = readWordFile("D:/data/test/img.docx");
			content.forEach(c -> {
				System.out.println(c);
			});
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
